package com.ea.admin.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.ea.admin.pojo.vo.tutelage.AdaptiveWarningInfoVo;
import com.ea.admin.pojo.vo.tutelage.ResponseWarningInfoVo;
import com.ea.admin.pojo.vo.tutelage.RiskWarningInfoVo;
import com.ea.admin.service.*;
import com.ea.admin.utils.CustomCellWriteHeightConfig;
import com.ea.admin.utils.CustomCellWriteWeightConfig;
import com.ea.admin.utils.ExcelUtils;
import com.ea.common.report.ReportFeign;
import com.ea.common.report.pojo.param.GetWarningInfoLongParam;
import com.ea.common.report.pojo.vo.GetPropertiesListVo;
import com.ea.common.report.pojo.vo.GetWarningInfoVo;
import com.ea.common.result.BizException;
import com.ea.common.result.ErrorCode;
import com.ea.common.result.Result;
import org.springframework.stereotype.Service;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

@Service
public class WarningServiceImpl implements WarningService {
    @Resource
    CompanyPermissionService companyPermissionService;
    @Resource
    DeptPermissionService deptPermissionService;
    @Resource
    PermissionService permissionService;
    @Resource
    PositionService positionService;
    @Resource
    CompanyService companyService;
    @Resource
    ReportFeign reportFeign;

    @Override
    public GetWarningInfoVo getWarningInfoVo(Long accountId,List<Long> companyIdList, List<Long> deptIdList, List<Long> positionIdList, List<Long> propertiesIdList, String name, List<Integer> warningTypeList, Integer page, Integer pageSize) {
        // 查询用户权限
        PermissionServiceImpl.PermissionList checked = permissionService
                .checkAndRefreshPermissionList(companyIdList, deptIdList, positionIdList, accountId);
        companyIdList = checked.companyIdList;
        deptIdList = checked.deptIdList;
        positionIdList = checked.positionIdList;

        // 查出所有下级单位
        List<Long> queryCompanyIdList = companyPermissionService.getSubCompanyIdList(accountId, companyIdList);
        // 查出所有下级部门
        List<Long> queryDeptIdList = deptPermissionService.getSubDepartmentIdList(accountId, queryCompanyIdList, deptIdList);

        List<Integer> allWarningTypeList = new ArrayList<>();
        allWarningTypeList.add(1);
        allWarningTypeList.add(2);
        allWarningTypeList.add(3);

        if (warningTypeList != null && !warningTypeList.isEmpty() && !new HashSet<>(allWarningTypeList).containsAll(warningTypeList)) {
            throw new BizException(ErrorCode.USER_PARAM_ERROR_WARNING_TYPE_ERROR);
        } else if (warningTypeList == null || warningTypeList.isEmpty()) {
            warningTypeList = allWarningTypeList;
        }

        if (pageSize == null) {
            // 公司的总人数
            pageSize = companyService.getCompanyCountByIdList(companyIdList);

        }

        Result<GetWarningInfoVo> reportFeignWarningInfoVo = reportFeign.getWarningInfoVo(
              new GetWarningInfoLongParam(queryCompanyIdList, queryDeptIdList,positionIdList,propertiesIdList,
                      name,warningTypeList,page,pageSize));
        if (reportFeignWarningInfoVo == null || reportFeignWarningInfoVo.getData() == null || reportFeignWarningInfoVo.getCode() != ErrorCode.NO_ERROR.getCode()) {
            throw new BizException(ErrorCode.TPS_DOWNSTREAM_SERVICE_ERROR);
        }

        return reportFeignWarningInfoVo.getData();
    }



    @Override
    public void exportWarningInfoVo(Long accountId, Integer warningType, HttpServletResponse response) {
        List<Integer> warningTypeList = new ArrayList<>();
        warningTypeList.add(warningType);

        GetWarningInfoVo vo = getWarningInfoVo(accountId, null, null, null,null, null, warningTypeList, 1, Integer.MAX_VALUE);

        if (warningType == 1) {
            exportResponseWarningVo(vo, response);
        } else if (warningType == 2) {
            exportAdaptiveWarningVo(vo, response);
        } else if (warningType == 3) {
            exportRiskWarningVo(vo, response);
        }
    }

    @Override
    public GetPropertiesListVo getPropertiesList() {
        Result<GetPropertiesListVo> reportFeignWarningInfoVo = reportFeign.getPropertiesList();
        if (reportFeignWarningInfoVo == null || reportFeignWarningInfoVo.getData() == null || reportFeignWarningInfoVo.getCode() != ErrorCode.NO_ERROR.getCode()) {
            throw new BizException(ErrorCode.TPS_DOWNSTREAM_SERVICE_ERROR);
        }
        return reportFeignWarningInfoVo.getData();
    }

    private void exportRiskWarningVo(GetWarningInfoVo vo, HttpServletResponse response) {
        List<RiskWarningInfoVo> excelList = new ArrayList<>();
        if (vo != null && vo.getItems() != null && !vo.getItems().isEmpty()) {
            // 导出
            vo.getItems().forEach(item -> {
                RiskWarningInfoVo infoVo = new RiskWarningInfoVo();
                infoVo.setName(item.getName());
                infoVo.setSex(item.getSex());
                infoVo.setAge(item.getAge());
                infoVo.setCompanyName(item.getCompanyName());
                infoVo.setDepartmentName(item.getDepartmentName());
                infoVo.setPositionName(item.getPositionName());
                if (item.getWarningType() == 0) {
                    infoVo.setWarningType("正常");
                } else if (item.getWarningType() == 1) {
                    infoVo.setWarningType("应答性预警");
                } else if (item.getWarningType() == 2) {
                    infoVo.setWarningType("适应性预警");
                } else if (item.getWarningType() == 3) {
                    infoVo.setWarningType("风险性预警");
                }
                if (item.getItems() != null && !item.getItems().isEmpty()) {
                    StringBuffer stringBuffer = new StringBuffer();
                    item.getItems().forEach(warningPropertiesVo -> {
                        stringBuffer.append(warningPropertiesVo.getPropertiesName()).append(" ");
                        if (warningPropertiesVo.getCompare() == 1) {
                            stringBuffer.append("↓ ");
                        } else if (warningPropertiesVo.getCompare() == 2) {
                            stringBuffer.append("↑ ");
                        }
                    });
                    infoVo.setWarningProperties(stringBuffer.substring(0, stringBuffer.length() - 1));
                }
                excelList.add(infoVo);
            });
        }

        try {
            response.reset();
            String fName = "预警名单.xlsx";
            String fileName = new String(fName.getBytes("gb2312"), "ISO8859-1");
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);

            // 这里注册的 CustomCellWriteHandler工具类是用来在excel中适应内容自动调整表格宽度的
            ExcelWriter writer = EasyExcel.write(response.getOutputStream())
                    .registerWriteHandler(new CustomCellWriteHeightConfig())
                    .registerWriteHandler(new CustomCellWriteWeightConfig())
                    .registerWriteHandler(ExcelUtils.getCellStyle())
                    .build();
            WriteSheet sheet = EasyExcel.writerSheet(0, "风险性预警名单")
                    .head(RiskWarningInfoVo.class).build();
            writer.write(excelList, sheet);
            writer.finish();
        } catch (Exception e) {
            throw new BizException(ErrorCode.SYSTEM_ERROR_FILE_EXPORT_ERROR);
        }
    }

    private void exportAdaptiveWarningVo(GetWarningInfoVo vo, HttpServletResponse response) {
        List<AdaptiveWarningInfoVo> excelList = new ArrayList<>();
        if (vo != null && vo.getItems() != null && !vo.getItems().isEmpty()) {
            // 导出
            vo.getItems().forEach(item -> {
                AdaptiveWarningInfoVo infoVo = new AdaptiveWarningInfoVo();
                infoVo.setName(item.getName());
                infoVo.setSex(item.getSex());
                infoVo.setAge(item.getAge());
                infoVo.setCompanyName(item.getCompanyName());
                infoVo.setDepartmentName(item.getDepartmentName());
                infoVo.setPositionName(item.getPositionName());
                if (item.getWarningType() == 0) {
                    infoVo.setWarningType("正常");
                } else if (item.getWarningType() == 1) {
                    infoVo.setWarningType("应答性预警");
                } else if (item.getWarningType() == 2) {
                    infoVo.setWarningType("适应性预警");
                } else if (item.getWarningType() == 3) {
                    infoVo.setWarningType("风险性预警");
                }
                if (item.getItems() != null && !item.getItems().isEmpty()) {
                    StringBuffer stringBuffer = new StringBuffer();
                    item.getItems().forEach(warningPropertiesVo -> {
                        stringBuffer.append(warningPropertiesVo.getPropertiesName()).append(" ");
                        if (warningPropertiesVo.getCompare() == 1) {
                            stringBuffer.append("↓ ");
                        } else if (warningPropertiesVo.getCompare() == 2) {
                            stringBuffer.append("↑ ");
                        }
                    });
                    infoVo.setWarningProperties(stringBuffer.substring(0, stringBuffer.length() - 1));
                }
                excelList.add(infoVo);
            });
        }

        try {
            response.reset();
            String fName = "预警名单.xlsx";
            String fileName = new String(fName.getBytes("gb2312"), "ISO8859-1");
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);

            // 这里注册的 CustomCellWriteHandler工具类是用来在excel中适应内容自动调整表格宽度的
            ExcelWriter writer = EasyExcel.write(response.getOutputStream())
                    .registerWriteHandler(new CustomCellWriteHeightConfig())
                    .registerWriteHandler(new CustomCellWriteWeightConfig())
                    .registerWriteHandler(ExcelUtils.getCellStyle())
                    .build();
            WriteSheet sheet = EasyExcel.writerSheet(0, "适应性预警名单")
                    .head(AdaptiveWarningInfoVo.class).build();
            writer.write(excelList, sheet);
            writer.finish();
        } catch (Exception e) {
            throw new BizException(ErrorCode.SYSTEM_ERROR_FILE_EXPORT_ERROR);
        }
    }

    private void exportResponseWarningVo(GetWarningInfoVo vo, HttpServletResponse response) {
        List<ResponseWarningInfoVo> excelList = new ArrayList<>();


        if (vo != null && vo.getItems() != null && !vo.getItems().isEmpty()) {
            // 导出
            vo.getItems().forEach(item -> {
                ResponseWarningInfoVo infoVo = new ResponseWarningInfoVo();
                infoVo.setName(item.getName());
                infoVo.setSex(item.getSex());
                infoVo.setAge(item.getAge());
                infoVo.setCompanyName(item.getCompanyName());
                infoVo.setDepartmentName(item.getDepartmentName());
                infoVo.setPositionName(item.getPositionName());
                if (item.getWarningType() == 0) {
                    infoVo.setWarningType("正常");
                } else if (item.getWarningType() == 1) {
                    infoVo.setWarningType("应答性预警");
                } else if (item.getWarningType() == 2) {
                    infoVo.setWarningType("适应性预警");
                } else if (item.getWarningType() == 3) {
                    infoVo.setWarningType("风险性预警");
                }
                if (item.getItems() != null && !item.getItems().isEmpty()) {
                    StringBuffer stringBuffer = new StringBuffer();
                    item.getItems().forEach(warningPropertiesVo -> {
                        stringBuffer.append(warningPropertiesVo.getPropertiesName()).append(" ");
                        if (warningPropertiesVo.getCompare() == 1) {
                            stringBuffer.append("↓ ");
                        } else if (warningPropertiesVo.getCompare() == 2) {
                            stringBuffer.append("↑ ");
                        }
                    });
                    infoVo.setWarningProperties(stringBuffer.substring(0, stringBuffer.length() - 1));
                }
                excelList.add(infoVo);
            });
        }

        try {
            response.reset();
            String fName = "预警名单.xlsx";
            String fileName = new String(fName.getBytes("gb2312"), "ISO8859-1");
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);

            // 这里注册的 CustomCellWriteHandler工具类是用来在excel中适应内容自动调整表格宽度的
            ExcelWriter writer = EasyExcel.write(response.getOutputStream())
                    .registerWriteHandler(new CustomCellWriteHeightConfig())
                    .registerWriteHandler(new CustomCellWriteWeightConfig())
                    .registerWriteHandler(ExcelUtils.getCellStyle())
                    .build();
            WriteSheet sheet = EasyExcel.writerSheet(0, "应答性预警名单")
                    .head(ResponseWarningInfoVo.class).build();
            writer.write(excelList, sheet);
            writer.finish();
        } catch (Exception e) {
            throw new BizException(ErrorCode.SYSTEM_ERROR_FILE_EXPORT_ERROR);
        }
    }
}
